package news.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import news.entity.Comment;
import news.util.DBUtil;

import org.news.dao.CommentDao;

public class CommentDaoImpl implements CommentDao {

	@Override
	public List<Comment> getCommentByCnid(int cnid) {
		List<Comment> list = new ArrayList<Comment>();
		Connection con = DBUtil.getConnection();
		ResultSet rs = null;
		PreparedStatement ps = null;
		String sql = "SELECT * FROM comments WHERE cnid = ? ;";
		Comment news = null;
		try {
			ps = con.prepareStatement(sql);
			ps.setInt(1, cnid);
			rs = ps.executeQuery();
			while (rs.next()) {
				news = new Comment();
				news.setCid(rs.getInt("cid"));
				news.setCnid(rs.getInt("cnid"));
				news.setCcontent(rs.getString("ccontent"));
				news.setCdate(rs.getTimestamp("cdate"));
				news.setCip(rs.getString("cip"));
				news.setCauthor(rs.getString("cauthor"));
				list.add(news);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, ps, rs);
		}
		return list;
	}

	@Override
	public int addComment(Comment comment) {
		Connection con = DBUtil.getConnection();
		int rs = 0;
		PreparedStatement ps = null;
		String sql = "insert into comments(cnid,ccontent,cdate,cip,cauthor) values(?,?,now(),?,?);";
		try {
			ps = con.prepareStatement(sql);
			ps.setInt(1, comment.getCnid());
			ps.setString(2, comment.getCcontent());
			ps.setString(3, comment.getCip());
			ps.setString(4, comment.getCauthor());
			rs = ps.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, ps, null);
		}
		return rs;
	}

}
